import React, { useState } from 'react'
import { Upload, message } from 'antd'
import { InboxOutlined } from '@ant-design/icons'

const { Dragger } = Upload

interface UploadProp {
  getFileIds: (ids: any[]) => void // Define the type of ids as needed
}

const App: React.FC<UploadProp> = ({ getFileIds }) => {
  const [fileList, setFileList] = useState([])

  const props = {
    name: 'file',
    multiple: true,
    fileList, // Control file list via state
    customRequest: (options) => {
      const { file, onSuccess, onError } = options
      const formData = new FormData()
      formData.append('file', file) // Add file to FormData

      fetch('http://localhost:8090/file/temUpload', {
        method: 'POST',
        body: formData,
      })
        .then((response) => {
          if (!response.ok) {
            throw new Error('Upload failed')
          }
          return response.json()
        })
        .then((data) => {
          // Assuming data.data contains the file ID
          const newFileList = [
            ...fileList,
            {
              uid: file.uid,
              name: file.name,
              status: 'done', // Mark status as done
              response: data, // Optional: store response data for further use
              percentage: 100, // Percentage could help with progress indication
            },
          ]
          setFileList(newFileList)
          getFileIds(newFileList.map((f) => f.response.data)) // Collect IDs for parent component
          onSuccess(data, file) // Call onSuccess to notify completion
        })
        .catch((error) => {
          console.error(error)
          const newFileList = fileList.map((item) => {
            if (item.uid === file.uid) {
              return { ...item, status: 'error' } // Mark status as error
            }
            return item
          })
          setFileList(newFileList)
          onError(error) // Call onError to notify failure
        })
    },
    onDrop(e) {
      console.log('Dropped files', e.dataTransfer.files)
    },
    onRemove: (file) => {
      setFileList((current) => current.filter((item) => item.uid !== file.uid)) // Remove file from list
    },
    progress: {
      // Additional upload progress feature
      strokeColor: {
        '0%': '#108ee9',
        '100%': '#87d068',
      },
      strokeWidth: 3,
      steps: 1, // Number of steps to show if needed
    },
  }

  return (
    <Dragger {...props}>
      <p className="ant-upload-drag-icon">
        <InboxOutlined />
      </p>
      <p className="ant-upload-text">
        Click or drag file to this area to upload
      </p>
      <p className="ant-upload-hint">
        Support for a single or bulk upload. Strictly prohibited from uploading
        company data or other banned files.
      </p>
    </Dragger>
  )
}

export default App
